package ldh.im.fxbase.service;

import ldh.im.dto.business.item.UserInfoItem;
import ldh.im.fxbase.dao.ImUserDao;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.data.pojo.status.ImSexEnum;
import ldh.im.fxbase.data.pojo.status.ImUserStatus;
import ldh.im.fxbase.util.BeanFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ImUserService {

    private ImUserDao imUserDao = BeanFactory.getInstance().getBean(ImUserDao.class);

    public void saveOrUpdates(List<UserInfoItem> userInfoItems) throws SQLException {
        List<ImUser> imUserList = userInfoItems.stream().map(this::toUser).collect(Collectors.toList());
        List<String> userIds = imUserList.stream().map(u->u.getUserId()).collect(Collectors.toList());

        List<ImUser> dbUsers = imUserDao.getUserByIds(userIds);
        Map<String, ImUser> dbUserMap = dbUsers.stream().collect(Collectors.toMap(ImUser::getUserId, Function.identity()));

        List<ImUser> insertImUsers = new ArrayList<>();
        List<ImUser> updateImUsers = new ArrayList<>();
        for(ImUser imUser : imUserList) {
            ImUser dbImUser = dbUserMap.get(imUser.getUserId());
            if (dbImUser == null) {
                insertImUsers.add(imUser);
            } else {
                imUser.setId(dbImUser.getId());
            }
        }
        imUserDao.batchInserts(insertImUsers);
        imUserDao.batchUpdates(updateImUsers);
    }

    private ImUser toUser(UserInfoItem userInfoItem) {
        ImUser imUser = new ImUser();
        imUser.setUserId(userInfoItem.getUserId());
        imUser.setUserName(userInfoItem.getUserName());
        imUser.setDepartmentCode(userInfoItem.getDepartmentCode());
        imUser.setDescription(userInfoItem.getMotto());
        imUser.setStatus(ImUserStatus.valueOf(userInfoItem.getStatus().name()));
        imUser.setSex(ImSexEnum.wrap(userInfoItem.getSex()));
        imUser.setMobile(userInfoItem.getMobile());
        imUser.setHeadImg(userInfoItem.getHeadImg());
        if (userInfoItem.getFirstLetter() != null) {
            imUser.setFirstLetter(userInfoItem.getFirstLetter().toString());
        }

        return imUser;
    }
}
